<!-- eslint-disable vue/valid-v-slot -->
<!-- eslint-disable vue/no-lone-template -->
<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader ref="tableHeaderRef" :show-filter="false">
          <template #search-content>
            <a-form ref="seachForm" :model="form">
              <a-row :gutter="24">
                <a-col :span="4">
                  <a-form-item field="name" hide-label>
                    <a-input
                      v-model="form.name"
                      class="width100"
                      placeholder="请输入渠道名称"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="api" hide-label>
                    <a-select
                      class="width100"
                      v-model="form.api"
                      placeholder="请选择渠道类型"
                      allow-clear
                    >
                      <a-option :value="1">第三方</a-option>
                      <a-option :value="0">流量池</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="4">
                  <a-form-item field="polling" hide-label>
                    <a-select
                      class="width100"
                      v-model="form.polling"
                      placeholder="请选择轮询状态"
                      allow-clear
                    >
                      <a-option :value="1">开启</a-option>
                      <a-option :value="0">关闭</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="orderSubmit" hide-label>
                    <a-select
                      class="width100"
                      v-model="form.orderSubmit"
                      placeholder="请选择订单提交状态"
                      allow-clear
                    >
                      <a-option :value="1">开启</a-option>
                      <a-option :value="0">关闭</a-option>
                    </a-select>
                  </a-form-item>
                </a-col> -->
                <a-col :span="4">
                  <a-form-item field="encoding" hide-label>
                    <a-select
                      class="width100"
                      v-model="form.encoding"
                      placeholder="请选择渠道系统"
                      allow-clear
                      allow-search
                    >
                      <a-option
                        v-for="item in treeData.list"
                        :key="item.name"
                        :value="item.encoding"
                        >{{ item.name }}</a-option
                      >
                    </a-select>
                  </a-form-item>
                </a-col>

                <a-col :span="4">
                  <a-form-item field="addTime" hide-label>
                    <a-date-picker
                      class="width100"
                      v-model="form.addTime"
                      show-time
                      :disabledDate="changeTraceEnd"
                      placeholder="请选择开始创建时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (form.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (form.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                      format="YYYY-MM-DD HH:mm:ss"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="endTime" hide-label>
                    <a-date-picker
                      class="width100"
                      v-model="form.endTime"
                      show-time
                      :disabledDate="changeTraceStart"
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (form.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (form.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                      placeholder="请选择结束创建时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="addBalance" hide-label>
                    <a-input-group style="width: 100%">
                      <a-input v-model="form.addBalance" placeholder="开始余额" allow-clear />
                      <a-input v-model="form.endBalance" placeholder="结束余额" allow-clear />
                    </a-input-group>
                  </a-form-item>
                </a-col>
                <a-col :span="4" :offset="20">
                  <a-form-item content-class=" flex justify-end" field="btns" hide-label>
                    <a-space :size="15">
                      <a-button
                        type="primary"
                        v-permission="channelList"
                        html-type="submit"
                        @click="doRefresh(1)"
                        ><template #icon> <icon-search /> </template>搜索</a-button
                      >
                      <a-button v-permission="channelList" @click="resetSeach"
                        ><template #icon>
                          <icon-sync theme="outline" size="14" />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>重置</template></a-button
                      >
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </template>
        </TableHeader>
      </template>
      <template #table-config>
        <a-space :size="15">
          <a-button
            v-permission="addChannel"
            type="primary"
            @click="onAddItem"
            @contextmenu.prevent.stop=";(modal.visibles = true), (addTitles = '新建渠道')"
          >
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>新建</template>
          </a-button>
          <a-button
            v-permission="exportChannelList"
            type="outline"
            @click="exportChannelLists"
            :loading="loading"
          >
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>导出</template>
          </a-button>
        </a-space>
        <a-space :size="15">
          <TableConfig
            @update-border="onUpdateBorder"
            @update-striped="onUpdateStriped"
            @refresh="doRefresh"
          />
        </a-space>
      </template>
      <template #default>
        <a-table
          :bordered="{ wrapper: true, cell: tables.bordered }"
          :stripe="(tables.striped as boolean)"
          :loading="tables.tableLoading"
          :data="table.dataList"
          :pagination="false"
          :column-resizable="true"
          :rowKey="rowKey"
          :columns="tableColumns.list"
          table-layout-fixed
          :show-empty-tree="false"
          :hide-expand-button-on-empty="true"
          :default-expand-all-rows="false"
          :isLeaf="false"
        >
          <template #columns>
            <a-table-column
              v-for="item of tableColumns.list"
              :key="item.key"
              :align="item.align"
              :title="(item.title as string)"
              :width="item.width"
              :data-index="(item.key as string)"
              :fixed="item.fixed"
              :ellipsis="true"
              :tooltip="true"
            >
              <template v-if="item.key === 'api'" #cell="{ record }">
                <a-space>
                  <div v-if="record.api" color="arcoblue">第三方</div>
                  <div v-else color="red">流量池</div>
                </a-space>
              </template>
              <template v-if="item.key === 'cardStatistics'" #cell="{ record }">
                <a-space>
                  {{ record.cardStatistics.total }}
                </a-space>
              </template>
              <template v-if="item.key === 'orderSubmit'" #cell="{ record }">
                <a-space>
                  <a-tag v-if="record.orderSubmit" color="arcoblue">开启</a-tag>
                  <a-tag v-else color="red">关闭</a-tag>
                </a-space>
              </template>
              <template v-if="item.key === 'nextSubmit'" #cell="{ record }">
                <a-space>
                  <a-tag v-if="record.nextSubmit" color="arcoblue">开启</a-tag>
                  <a-tag v-else color="red">关闭</a-tag>
                </a-space>
              </template>
              <template v-if="item.key === 'polling'" #cell="{ record }">
                <a-space>
                  <a-tag v-if="record.polling" color="arcoblue">开启</a-tag>
                  <a-tag v-else color="red">关闭</a-tag>
                </a-space>
              </template>
              <template v-if="item.key === 'actions'" #cell="{ record }">
                <a-space style="display: flex; flex-wrap: wrap">
                  <a-button
                    size="small"
                    type="text"
                    class="butten"
                    v-permission="updateChannel"
                    @click="infoDepartments(record)"
                    @contextmenu.prevent.stop="towCss(record)"
                  >
                    编辑
                  </a-button>
                  <a-button
                    size="small"
                    class="butten"
                    type="text"
                    v-permission="verificationChannel"
                    @click="verificationChannels(record.id)"
                  >
                    验证
                  </a-button>
                  <a-button
                    size="small"
                    v-permission="addChannel"
                    class="butten"
                    type="text"
                    @click="copy(record)"
                  >
                    复制
                  </a-button>
                  <a-button
                    size="small"
                    class="butten"
                    type="text"
                    v-permission="balanceChannel"
                    @click="balanceChannels(record.id)"
                  >
                    余额
                  </a-button>
                  <a-button
                    v-permission="threadSet"
                    size="small"
                    class="butten"
                    type="text"
                    @click="thread(record)"
                  >
                    网络
                  </a-button>
                  <a-button
                    v-permission="'/app/channel/message'"
                    size="small"
                    class="butten"
                    type="text"
                    @click="SSE(record)"
                  >
                    抓包
                  </a-button>
                  <a-button
                    size="small"
                    v-permission="deleteChannel"
                    class="butten"
                    type="text"
                    @click="onDeleteItem(record)"
                  >
                    删除
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
      <template #footer>
        <TableFooter ref="tableFooterRef" :pagination="pagination" />
      </template>
    </TableBody>
    <a-modal
      v-model:visible="modal.visible"
      width="600px"
      :mask-closable="false"
      @before-close="beforeClose"
      title-align="start"
    >
      <template #title> {{ addTitles }} </template>
      <div>
        <a-form ref="infoRef" :labelCol="{ span: 12 }" :model="info.info" :auto-label-width="true">
          <a-form-item
            label="渠道系统"
            field="encoding"
            :rules="[{ required: true, message: '请选择渠道系统' }]"
            asterisk-position="end"
            :validate-trigger="['change']"
          >
            <a-select
              placeholder="请选择渠道系统"
              v-model="info.info.encoding"
              allow-search
              @change="encodingFn"
            >
              <a-option v-for="item in treeData.list" :key="item.name" :value="item.encoding">{{
                item.name
              }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="渠道名称"
            field="name"
            :rules="[
              { required: true, message: '请输入渠道名称' },
              { minLength: 1, maxLength: 30, message: '长度在 1 - 20个字符' },
            ]"
            asterisk-position="end"
          >
            <a-input placeholder="请输入渠道名称" v-model.trim="info.info.name" />
          </a-form-item>
          <a-form-item label="备注" field="remarks" style="width: 100%">
            <a-textarea placeholder="请输入备注" v-model.trim="info.info.remarks" allow-clear />
          </a-form-item>
          <a-divider dashed style="margin-bottom: 25px">对接参数</a-divider>
          <a-form-item v-if="show" label="token" field="otherEncoding">
            <a-select
              @change="encodingFns"
              placeholder="请选择类型"
              v-model="info.info.otherEncoding"
              allow-clear
              allow-search
              @clear="clearEncoding"
            >
              <a-option v-for="item in list" :key="item.name" :value="item.encoding">{{
                item.name
              }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            v-if="show && info.info.otherEncoding"
            label="第三方接口"
            field="otherUrl"
            :rules="rulesssssssss"
          >
            <a-input placeholder="请输入第三方接口" v-model.trim="info.info.otherUrl" />
          </a-form-item>
          <a-form-item
            v-for="item in info.info.parameters"
            :key="item.key"
            :label="item.name"
            :field="item.key"
          >
            <a-input :placeholder="`请输入${item.name}`" v-model.trim="item.value" />
          </a-form-item>
          <a-form-item
            v-for="item in info.info.otherParameters"
            :key="item.key"
            :label="item.name"
            :field="item.key"
          >
            <a-input :placeholder="`请输入${item.name}`" v-model.trim="item.value" />
          </a-form-item>
          <a-form-item label="接口地址" field="url" :rules="rulesssssssss">
            <a-input placeholder="请输入接口地址" v-model.trim="info.info.url" />
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <a-space v-if="info.info.id">
          <a-button @click="beforeClose">取消</a-button>
          <a-button type="primary" @click="handleSubmit">确定</a-button>
        </a-space>
        <div v-else style="display: flex; justify-content: space-between; width: 100%">
          <a-checkbox v-model="checked1">继续新建下一个渠道</a-checkbox>
          <a-space>
            <a-button @click="beforeClose">取消</a-button>
            <a-button type="primary" @click="handleSubmit">确定</a-button>
          </a-space>
        </div>
      </template>
    </a-modal>
    <!-- 复制渠道 -->
    <a-modal
      v-model:visible="copyVisible"
      title="复制渠道"
      width="600px"
      @before-close="copyCel"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="copyRef" :auto-label-width="true" :model="copyForm">
        <a-form-item field="name" label="渠道名称">
          {{ copyForm.name }}
        </a-form-item>
        <a-form-item field="copyType" label="复制类型">
          <a-radio-group class="radio-bcg" v-model="copyForm.copyType">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">一键复制</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">编辑并复制</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="copyForm.copyType == true"
          field="copyNum"
          label="复制数量"
          :rules="[{ required: true, message: '复制数量不能为空' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-input-number
            v-model="copyForm.copyNum"
            :min="1"
            placeholder="请输入复制数量"
            allow-clear
          />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="copyCel">取消</a-button>
          <a-button type="primary" @click="copyCancel">确定</a-button>
        </a-space>
      </template>
    </a-modal>
    <!-- 线程 -->
    <a-modal
      v-model:visible="threadVisible"
      title="时间设置"
      width="600px"
      @before-close="threadCel"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="threadRef" :auto-label-width="true" :model="threadForm">
        <a-form-item
          field="pollingTime"
          label="轮询间隔"
          :rules="[{ required: true, message: '请选择轮询间隔' }]"
          :validate-trigger="['change']"
          asterisk-position="end"
        >
          <a-select v-model="threadForm.pollingTime" placeholder="请选择轮询间隔" allow-clear>
            <a-option :value="0">1分钟执行一次</a-option>
            <a-option :value="1">5分钟执行一次</a-option>
            <a-option :value="2">10分钟执行一次</a-option>
            <a-option :value="3">20分钟执行一次</a-option>
            <a-option :value="4">30分钟执行一次</a-option>
            <a-option :value="5">1小时执行一次</a-option>
            <a-option :value="6">3小时执行一次</a-option>
            <a-option :value="7">6小时执行一次</a-option>
            <a-option :value="8">8小时执行一次</a-option>
            <a-option :value="9">12小时执行一次</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="运行线程"
          field="pollingThread"
          :rules="[{ required: true, message: '请输入运行线程' }]"
          :validate-trigger="['change']"
          asterisk-position="end"
        >
          <a-input-number
            hide-button
            placeholder="请输入运行线程"
            v-model="threadForm.pollingThread"
          />
        </a-form-item>
        <a-form-item label="失败重试">
          <a-radio-group class="radio-bcg" v-model="threadForm.retryOnConnectionFailure">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">开启</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">关闭</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="连接时间"
          field="connectTimeout"
          :rules="[{ required: true, message: '请选择连接时间' }]"
          :validate-trigger="['change']"
          asterisk-position="end"
        >
          <a-input-number
            hide-button
            placeholder="请输入连接时间"
            v-model.trim="threadForm.connectTimeout"
          />
        </a-form-item>
        <a-form-item
          label="写入时间"
          field="writeTimeout"
          :rules="[{ required: true, message: '请选择写入时间' }]"
          :validate-trigger="['change']"
          asterisk-position="end"
        >
          <a-input-number
            hide-button
            placeholder="请输入写入时间"
            v-model.trim="threadForm.writeTimeout"
          />
        </a-form-item>
        <a-form-item
          label="读取时间"
          field="readTimeout"
          :rules="[{ required: true, message: '请选择读取时间' }]"
          :validate-trigger="['change']"
          asterisk-position="end"
        >
          <a-input-number
            hide-button
            placeholder="请输入读取时间"
            v-model.trim="threadForm.readTimeout"
          />
        </a-form-item>
        <a-form-item label="代理地址" field="proxyHost">
          <a-input hide-button placeholder="请输入代理地址" v-model.trim="threadForm.proxyHost" />
        </a-form-item>
        <a-form-item label="代理端口" field="proxyPort">
          <a-input hide-button placeholder="请输入代理端口" v-model.trim="threadForm.proxyPort" />
        </a-form-item>
        <a-form-item label="库存复机">
          <a-radio-group class="radio-bcg" v-model="threadForm.stockStart">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">开启</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">关闭</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="未实名复机">
          <a-radio-group class="radio-bcg" v-model="threadForm.noRealName">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">开启</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">关闭</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="待激活复机">
          <a-radio-group class="radio-bcg" v-model="threadForm.waitforStart">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">开启</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">关闭</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="返回数据">
          <a-radio-group class="radio-bcg" v-model="threadForm.realTime">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">实时数据</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">本地数据</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="threadCel">取消</a-button>
          <a-button type="primary" @click="threadCancel">确定</a-button>
        </a-space>
      </template>
    </a-modal>
    <!--抓包 -->
    <a-modal
      v-model:visible="showse"
      width="800px"
      :mask-closable="false"
      title-align="start"
      @before-close="close"
    >
      <template #title>
        {{ forms.name }}
      </template>
      <!-- <div class="alert">
        <div style="color: #fff">
          轮询数据： 成功数量：{{ forms.success }}张 失败数量：{{ forms.error }}张 成功率：{{
            Math.floor((forms.success / (forms.error + forms.success)) * 100)
          }}%
        </div>
      </div> -->
      <div> <a-divider dashed>实时数据</a-divider> </div>
      <div
        :class="top == -1 ? 'mail-container yin' : top >= 0 ? 'mail-container yin1' : ''"
        ref="scrollWrapperRef"
        @scroll="handleScroll"
        style="height: 500px; overflow-y: auto"
      >
        <div v-for="item in dataList" style="margin-top: 10px" :key="item">
          {{ item }}
        </div>
      </div>
      <template #footer>
        <a-space />
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import {
    channelList,
    encodingList,
    addChannel,
    deleteChannel,
    updateChannel,
    exportChannelList,
    verificationChannel,
    balanceChannel,
    threadSet,
  } from '@/api/url'

  import useCommonStore from '@/store/modules/common'
  import { post, formpost, get } from '@/api/http'
  import { usePagination, useRowKey, useTable } from '@/hooks/table'
  import { onMounted, reactive, ref } from 'vue'

  import _ from 'lodash-es'

  import { Message, Modal } from '@arco-design/web-vue'
  import { useRoute } from 'vue-router'
  //抓包
  const showse = ref(false)
  const forms: any = ref({})
  const source = ref()
  const dataList: any = ref([])
  const showsa = ref(true)
  function close() {
    showsa.value = false
    dataList.value = []
    source.value.close()
    showse.value = false
    console.log(111)
  }
  const SSE = (val: any) => {
    showse.value = true
    forms.value = val
    if (window.EventSource) {
      // if (showsa.value == true) {
      // } else {
      showsa.value = true
      // 建立连接
      source.value = new EventSource('/app/channel/message?id=' + val.id)
      /**
       * 连接一旦建立，就会触发open事件
       */

      source.value.onopen = function (e: any) {
        console.log('建立连接', e)
      }
      /**
       * 客户端收到服务器发来的数据
       */
      source.value.onmessage = function (e: any) {
        console.log(e)
        if (dataList.value.length < 1000) {
          dataList.value.unshift(e.data)
        } else {
          dataList.value.unshift(e.data)
          dataList.value.pop()
        }
      }
      /**
       * 如果发生通信错误（比如连接中断），就会触发error事件
       */
      source.value.onerror = function (e: any) {
        // showsa.value = false
        if (e.readyState === EventSource.CLOSED) {
          console.log('连接关闭')
        } else {
          Message.error('超时请重试')
          // renewForm.value = {}
          showse.value = false
          source.value.close()
        }
      }
      // }
    } else {
      console.log('浏览器不支持SSE')
    }
  }
  const top = ref(0)
  const scrollWrapperRef = ref() //滚动区域的父元素
  const handleScroll = () => {
    //滚动触发的事件
    const scrollWrapper = scrollWrapperRef.value // 获取滚动容器
    const { scrollTop, clientHeight, scrollHeight } = scrollWrapper // 获取滚动数据
    // console.log('scrollWrapper', scrollTop, clientHeight, scrollHeight)
    // 判断是否滚动到底部
    if (scrollTop == 0) {
      top.value = scrollTop
    } else if (scrollTop + clientHeight >= scrollHeight - 10) {
      top.value = -1
    }
  }
  const route = useRoute()
  const useCommon = useCommonStore()

  const table = useTable()

  const pagination = usePagination(doRefresh)

  const infoRef = ref()

  const copyRef = ref()

  const copyNum = ref(0)
  const show = ref(false)
  const list: any = ref([])

  const copyVisible = ref(false)
  const checked1 = ref(false)

  const threadVisible = ref(false)
  const expandable = {
    title: 'Expand',
    width: 0,
  }
  const threadForm = ref({
    pollingThread: 5,
    writeTimeout: 5,
    readTimeout: 5,
    connectTimeout: 5,
    retryOnConnectionFailure: true,
    proxyHost: '',
    proxyPort: '',
    pollingTime: '',
    stockStart: false,
    realTime: true,
    waitforStart: true,
    noRealName: false,
  })
  const threadRef = ref()
  const addTitles = ref('新建渠道')

  const copyForm = ref({
    id: '',
    name: '',
    copyType: true,
    copyNum: 1,
  })

  const loading = ref(false)

  const seachForm = ref()

  const modal = reactive({
    visible: false,
    key: '1',
    visibles: false,
  })

  const form = reactive({
    name: '', //渠道类型
    api: '', //订单提交
    orderSubmit: '', // 轮询状态
    polling: '', // 次月提交
    nextSubmit: '',
    addTime: '',
    endTime: '',
    addBalance: '',
    endBalance: '',
    encoding: '',
  })

  const tables = reactive({
    tableLoading: false,
    bordered: false,
    striped: false,
    expand: [1],
    isExpand: false,
  })

  const info: any = reactive({
    info: {
      name: '',
      encoding: '', //渠道编码
      url: '', //接口地址
      userName: '', //接口账号
      passWord: '', //接口密码
      key: '', //接口密钥
      api: 0, //渠道类型 0 流量池 1第三方
      remarks: '',
      parameters: [],
      otherParameters: [],
      otherEncoding: '',
      otherUrl: '',
    },
    disabled: false,
  })

  const treeData = reactive({
    list: [{ api: true, encoding: 'YINGMENG', name: '迎梦', url: 'http://www.yingmengyun.com' }],
    parentId: [],
    option: {},
  })

  // 接口地址
  const rulesssssssss = [
    {
      validator: (value: string, cb: (arg0: string) => void) => {
        return new Promise<void>((resolve) => {
          const rule1 = /(http|https):\/\/\S*/
          console.log(rule1.test(value))
          if (!rule1.test(value)) {
            cb('请输入正确的接口地址')
          }
          resolve()
        })
      },
    },
  ]

  const tableColumns: any = reactive({
    list: [
      {
        title: '渠道ID',
        key: 'id',
        dataIndex: 'id',
        align: 'left',
        checked: true,
        width: 100,
      },
      {
        title: '渠道名称',
        key: 'name',
        dataIndex: 'name',
        align: 'left',
        checked: true,
        width: 220,
      },
      {
        title: '渠道系统',
        key: 'encodingName',
        dataIndex: 'encodingName',
        align: 'left',
        checked: true,
        width: 220,
      },
      {
        title: '渠道余额',
        key: 'balance',
        dataIndex: 'balance',
        align: 'left',
        checked: true,
        width: 220,
      },
      {
        title: '卡板数量',
        key: 'cardStatistics',
        dataIndex: 'cardStatistics',
        align: 'left',
        checked: true,
        width: 200,
      },
      {
        title: '渠道类型',
        key: 'api',
        dataIndex: 'api',
        align: 'left',
        checked: true,
        width: 220,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        align: 'left',
        checked: true,
        width: 190,
      },
      {
        title: '操作',
        key: 'actions',
        dataIndex: 'actions',
        align: 'left',
        checked: true,
        width: 220,
        fixed: 'right',
      },
    ],
  })

  const rowKey = useRowKey('id')

  const encodingFn = (val: any) => {
    info.info.encoding = val
    info.info.otherEncoding = ''
    console.log(111111)
    info.info.otherParameters = null
    info.info.parameters = []
    treeData.list.forEach((item: any) => {
      if (item.encoding == val) {
        if (item.children) {
          show.value = true
          list.value = item.children
        } else {
          show.value = false
          info.info.api = item.api ? 1 : 0
          info.info.pool = false
        }
        info.info.parameters = item.parameters
        if (item.url) {
          info.info.url = item.url
        } else {
          info.info.url = ''
        }
      }
    })
  }
  function clearEncoding() {
    info.info.parameters = []
    info.info.otherParameters = []
    treeData.list.forEach((item: any) => {
      if (item.encoding == info.info.encoding) {
        if (item.children) {
          show.value = true
          list.value = item.children
        } else {
          show.value = false
          info.info.api = item.api ? 1 : 0
          info.info.pool = false
        }
        info.info.parameters = item.parameters
        if (item.url) {
          info.info.url = item.url
        } else {
          info.info.url = ''
        }
      }
    })
  }

  const encodingFns = (val: any) => {
    list.value.forEach((item: any) => {
      if (item.encoding == val) {
        info.info.parameters = item.parameters
        if (item.otherParameters) {
          info.info.otherParameters = item.otherParameters
        } else {
          info.info.otherParameters = null
        }
        info.info.pool = false
      }
    })
  }

  const resetSeach = () => {
    seachForm.value.resetFields()
    doRefresh(1)
  }

  const exportChannelLists = () => {
    loading.value = true
    useCommon
      .downLoads(exportChannelList, form, '渠道列表')
      .then(() => {
        loading.value = false
      })
      .catch(() => {
        loading.value = false
      })
  }

  const copy = (val: any) => {
    info.info = JSON.parse(JSON.stringify(val))
    copyForm.value.name = val.name
    info.info.id = ''
    copyVisible.value = true
  }

  const towCss = (val: any) => {
    info.info = JSON.parse(JSON.stringify(val))
    if (info.info.childrenData) {
      show.value = true
      list.value = val.childrenData
    }
    addTitles.value = '编辑渠道'
    modal.visibles = true
  }

  const thread = (val: any) => {
    threadForm.value = JSON.parse(JSON.stringify(val))
    threadVisible.value = true
  }

  const copyCel = () => {
    copyRef.value.resetFields()
    copyVisible.value = false
  }

  const threadCel = () => {
    threadRef.value.resetFields()
    threadVisible.value = false
  }

  const threadCancel = () => {
    threadRef.value.validate((error: any) => {
      if (!error) {
        formpost({
          url: threadSet,
          data: {
            ...threadForm.value,
          },
        }).then((res) => {
          if (res.code == 0) {
            Message.success(res.msg)
            threadCel()
            doRefresh()
          }
        })
      }
    })
  }

  const copyCancel = () => {
    copyRef.value.validate((error: any) => {
      if (!error) {
        if (copyForm.value.copyType == true) {
          const num = copyForm.value.copyNum
          for (let index = 0; index < num; index++) {
            addChannels()
          }
          copyRef.value.resetFields()
        } else {
          info.info.id = ''
          copyNum.value = 1
          copyRef.value.resetFields()
          copyVisible.value = false
          modal.visible = true
        }
      }
    })
  }

  const verificationChannels = (val: number) => {
    get({
      url: verificationChannel,
      data: {
        id: val,
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        doRefresh()
      }
    })
  }

  const balanceChannels = (val: number) => {
    get({
      url: balanceChannel,
      data: {
        id: val,
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        doRefresh()
      }
    })
  }

  const beforeClose = () => {
    infoRef.value.clearValidate()
    infoRef.value.resetFields()
    treeData.parentId = []
    info.info.id = ''
    info.info.parameters = []
    info.info.otherParameters = null
    show.value = false
    list.value = []
    info.info.otherUrl = ''
    modal.visible = false
    modal.visibles = false
    console.log(11111111111)
  }

  const handleSubmit = () => {
    info.info.name = info.info.name.split(/\s+/).join('')
    if (info.info.otherUrl) {
      info.info.otherUrl = info.info.otherUrl.split(/\s+/).join('')
    }
    info.info.url = info.info.url.split(/\s+/).join('')
    if (info.info.remarks) {
      info.info.remarks = info.info.remarks.split(/\s+/).join('')
    }
    info.info.parameters.forEach((item: any, index: any) => {
      info.info.parameters[index].value = item.value.split(/\s+/).join('')
    })
    infoRef.value.validate((error: any) => {
      if (!error) {
        if (info.info.id) {
          updateChannels()
        } else {
          addChannels()
        }
      } else {
        console.log(error)
      }
    })
  }

  const infoDepartments = (val: any) => {
    addTitles.value = '编辑渠道'
    info.info = JSON.parse(JSON.stringify(val))
    // info.info.api = val.api == true ? 1 : 0
    // info.info.api = val.api == true ? 1 : 0
    if (info.info.childrenData) {
      show.value = true
      list.value = val.childrenData
    }
    // console.log(info.info)
    // if (val.parentId) {
    //   treeData.parentId.push(val.parentId)
    //   info.disabled = true
    // }
    modal.visible = true
  }

  const updateChannels = () => {
    post({
      url: updateChannel,
      data: {
        ...info.info,
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        beforeClose()
        doRefresh()
      }
    })
  }

  const addChannels = () => {
    post({
      url: addChannel,
      data: {
        ...info.info,
      },
    }).then((res) => {
      if (res.code == 0) {
        if (checked1.value == true) {
          infoRef.value.clearValidate()
          infoRef.value.resetFields()
          treeData.parentId = []
          checked1.value = false
          info.info.id = ''
          info.info.parameters = []
          show.value = false
          list.value = []
          Message.success('新建成功，当前已开始新建新的渠道')
          doRefresh()
        } else {
          Message.success(res.msg)
          copyCel()
          beforeClose()
          doRefresh()
        }
      }
    })
  }

  const encodingLists = () => {
    get({
      url: encodingList,
      data: () => {
        return {}
      },
    }).then((res) => {
      treeData.list = res.data
      return res.data
    })
  }

  function onUpdateBorder(isBordered: boolean) {
    tables.bordered = isBordered
  }

  function onUpdateStriped(isStriped: boolean) {
    tables.striped = isStriped
  }

  function doRefresh(value?: number) {
    tables.tableLoading = true
    if (value) {
      pagination.page = value
    }
    get({
      url: channelList,
      data: {
        ...form,
        page: pagination.page,
        size: pagination.pageSize,
      },
    }).then((res) => {
      tables.tableLoading = false
      encodingLists()
      res.data.list.forEach((item: any) => {
        item.childrenData = item.children
        delete item.children
      })
      console.log(res.data.list)
      table.handleSuccess(res.data.list)
      pagination.setTotalSize((res.data as any).totalSize)
      return res.data.list
    })
  }

  //删除渠道
  const deleteChannels = (val: number) => {
    get({
      url: deleteChannel,
      data: {
        id: val,
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        doRefresh()
      }
    })
  }

  const onDeleteItem = (item: any) => {
    Modal.warning({
      title: '操作确认',
      content: '确定要删除此渠道？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '确定',
      onOk() {
        deleteChannels(item.id)
      },
    })
  }

  function onAddItem() {
    info.info.id = ''
    info.info.parameters = []
    info.info.otherParameters = null
    addTitles.value = '新建渠道'
    modal.visible = true
  }

  //跟踪API开始时间限制结束时间
  function changeTraceEnd(time: any) {
    return time.getTime() > new Date(form.endTime).getTime() //大于结束时间的不选
  }
  //跟踪API结束时间限制开始时间
  function changeTraceStart(time: any) {
    return time.getTime() < new Date(form.addTime).getTime() //小于开始时间的不选
  }

  onMounted(async () => {
    if (history.state.name) {
      form.name = history.state.name
    }
    await doRefresh()
  })
</script>

<style lang="less" scoped>
  .yin {
    box-shadow: 0px 10px 10px -8px #0000001a inset;
  }
  .yin1 {
    box-shadow: 0px -10px 10px -8px #0000001a inset;
  }
  .main-container {
  }
  :deep(.arco-table-td-content button) {
    padding: 0px !important;
    margin-right: 8px;
    background: none !important;
  }
  // :deep(.arco-form-item-label) {
  //   width: 68px;
  //   text-align: right;
  // }
  :deep(.arco-table-cell-expand-icon) {
    justify-content: center;
  }

  :deep(.arco-tabs-tab-title) {
    width: 52px !important;
    text-align: center;
  }

  :deep(.arco-tabs-nav-type-capsule .arco-tabs-nav-tab-list) {
    padding: 12px 12px;
  }
  .tabs {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 40px;
    margin-bottom: 20px;

    .button {
      box-sizing: border-box;
      padding-bottom: 5px;
    }
  }

  .action {
    color: #009dff;
    border-bottom: 3px solid #009dff;
  }

  .butten {
    margin-right: 5px;
    padding: 0px;
  }

  .input516 {
    width: 470px;
    margin-left: 20px;
  }
  :deep(.arco-divider-horizontal) {
    margin: 7px 0;
  }
  :deep(.arco-divider-text) {
    top: 0;
    line-height: 1;
  }
</style>
<style>
  .arco-drawer-body {
    padding: 0 !important;
  }
</style>
